<template>
  <el-dialog :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog tl-dialog-small" width="800px" @open="open" :append-to-body="true" :modal-append-to-body="true" @close="close">
    <el-form class="tl-form" ref="form" size="small" :model="model" :rules="rules" label-width="90px" :disabled="disableEditSubmit || readonly">
      <el-row v-if="isEditPeriod">
        <el-col :span="24">
          <el-alert :closable="false" type="warning" style="margin-bottom:10px" title="修改周期任务，会将未开始的日程全部删除，重新生成，过期数据保持原样，请谨慎操作"> </el-alert>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="日程标题" prop="name" :rules="rules.validateRequire">
            <el-input v-model="model.name" maxlength="50" show-word-limit class="input-with-select">
              <el-select v-model="model.scheduletype" filterable slot="prepend">
                <el-option v-for="item in codeModel.scheduletypeList" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="开始时间" prop="begintimeDate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.begintimeDate" type="date" placeholder="开始时间" @change="changeBeginDate" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="" label-width="10px" prop="begintimeTime" :rules="rules.validateRequire">
            <el-time-select
              v-model="model.begintimeTime"
              placeholder="选择时间"
              editable
              :clearable="false"
              @change="changeBeginTime"
              :picker-options="{
                start: '00:00',
                step: '00:05',
                end: '24:00'
              }"
            >
            </el-time-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" prop="endtimeDate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.endtimeDate" type="date" placeholder="结束时间" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="" label-width="10px" prop="endtimeTime" :rules="rules.validateRequire">
            <el-time-select
              v-model="model.endtimeTime"
              placeholder="选择时间"
              editable
              :picker-options="{
                start: '00:00',
                step: '00:05',
                end: '24:00'
              }"
            >
            </el-time-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!--周期-->
      <tl-period-config v-model="model" v-if="isAdd || isEditPeriod" :isEdit="isEditPeriod" ref="periodConfig"></tl-period-config>
      <!--消息提醒-->
      <tl-remind-config v-model="remindList"></tl-remind-config>
      <el-row>
        <el-col :span="24">
          <el-form-item label="日历标签" prop="tags">
            <div class="tag-container">
              <el-tag :key="tag" v-for="tag in tagList" :closable="!disableEditSubmit && !readonly" :disable-transitions="false" @close="handleClose(tag)">
                {{ tag }}
              </el-tag>
              <el-input class="input-new-tag" maxlength="10" placeholder="最多10个字" v-if="inputVisible" style="width:100px;" v-model="inputValue" ref="saveTagInput" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm"> </el-input>
              <el-button v-else circle @click="showInput" icon="el-icon-plus" size="mini"></el-button>
              <tl-help>
                可自定义设置标签，便于搜索和提醒，字数最多不超过10个。如：带电脑、需要录音等。
              </tl-help>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="日程接收人">
            <tl-mulit-user-select v-model="users" :displayShare="true" :displayMulit="hasMulitUserRole" :disabled="disableEditSubmit || readonly"></tl-mulit-user-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!isAdd && model.handleusercode !== ownerUser.code">
        <el-col :span="24">
          <el-form-item label="日程安排人">
            {{ model.handleusername }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="添加描述" prop="content">
            <el-input v-model="model.content" type="textarea" :rows="3" maxlength="500" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="地点" prop="place">
            <el-input v-model="model.place" type="input" :rows="1" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="overflow:hidden">
      <el-button type="text" @click="doCancelEdit" size="mini">取消</el-button>
      <el-button type="default" icon="el-icon-date" v-if="model.sourcetype === 'workTask' && !isHiddenPeriod && model.id" size="mini" @click="openPeriodList">查看该系列周期日程</el-button>
      <el-button type="primary" icon="el-icon-finished" @click="checkConflict" :loading="saveLoading" size="mini" v-if="!disableEditSubmit && !readonly">{{ isEditPeriod ? '保存周期日程' : '保存' }}</el-button>
    </div>
    <period-list ref="periodList" :ownerUser="ownerUser" :readonly="readonly" @closeAll="closeAll" @refresh="transRefresh"></period-list>
    <conflict-list ref="conflictList" :dataList="conflictList"></conflict-list>
  </el-dialog>
</template>

<script>
/** mixins */
import { mixin_edit } from '@tapui/mixins/mixin_edit'
import { mulitPlusScheduleRole } from '@/const/const'
/** 子组件 */
import tlRemindConfig from '@/components/common/remindConfig'
import tlPeriodConfig from '@/components/common/period'
import tlMulitUserSelect from '@/components/common/refMulitUserSelect'
import periodList from './periodList'
import conflictList from './conflictList'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { formatDate } from '@tapui/utils/date'
/** VUE配置 */
export default {
  mixins: [mixin_edit],
  components: { tlMulitUserSelect, tlRemindConfig, tlPeriodConfig, periodList, conflictList },
  data() {
    return {
      moduleTitle: '工作日程',
      urlPrefix: '/work/schedule/',
      url: {
        // 额外的url
        add: '/work/schedule/saveCalendar',
        edit: '/work/schedule/saveCalendar',
        editTask: '/work/task/update',
        editSchedule: '/work/schedule/saveCalendar',
        queryRemind: '/base/remindConfig/list',
        queryUser: '/base/permissionManage/queryList',
        loadTask: '/work/task/load',
        loadSchedule: '/work/schedule/load',
        queryConflict: '/base/permissionManage/checkTimeConflict'
      },
      // 提醒列表
      remindList: [],
      // 下面仨是标签相关
      inputVisible: false,
      inputValue: '',
      tagList: [],
      // 是否是修改周期日程
      isEditPeriod: false,
      qry_sourcetype: 'workSchedule',
      // 隐藏查看系列周期按钮，在周期列表中查看时，使用
      isHiddenPeriod: false,
      // 多人会议
      users: {
        usernames: '',
        usercodes: '',
        deptnames: '',
        deptcodes: '',
        teamids: '',
        teamnames: '',
        roleids: '',
        rolenames: '',
        sharecodes: '',
        sharenames: ''
      },
      // 冲突记录
      conflictList: [],
      conflictVisible: false
    }
  },
  props: {
    dateInfo: {
      type: Object,
      default: function() {
        return null
      }
    },
    transModel: {
      type: Object,
      default: function() {
        return null
      }
    },
    // 默认日程所属人
    ownerUser: {
      type: Object,
      default: function() {
        return {
          code: '',
          name: ''
        }
      }
    }
  },
  computed: {
    readonly() {
      return !this.isAdd && this.user.code !== this.model.handleusercode
    },
    // 是否有批量添加人员的权限
    hasMulitUserRole() {
      return this.$store.getters.roles.findIndex((m) => m === mulitPlusScheduleRole) > -1
    }
  },
  methods: {
    loaded() {
      // 页面加载完毕执行
      this.tagList = []
      this.$set(this.model, 'isPeriod', false)
      this.qry_sourcetype = 'workSchedule'
      if (!this.isAdd) {
        if (this.transModel !== null) {
          // 将简单编辑页的内容传递过来
          if (this.transModel.name) this.$set(this.model, 'name', this.transModel.name)
          if (this.transModel.begintime) this.$set(this.model, 'begintime', this.transModel.begintime)
          if (this.transModel.endtime) this.$set(this.model, 'endtime', this.transModel.endtime)
          if (this.transModel.scheduletype) this.$set(this.model, 'scheduletype', this.transModel.scheduletype)
          if (this.transModel.tags) this.$set(this.model, 'tags', this.transModel.tags)
          if (this.transModel.place) this.$set(this.model, 'place', this.transModel.place)
        }
        if (this.model.tags && this.model.tags.length > 0) {
          this.tagList = this.model.tags.split(',')
        }
        if (this.isEditPeriod) {
          this.model.isPeriod = true
          this.qry_sourcetype = 'workTask'
        }
        if (this.readonly || this.disableEditSubmit) {
          this.title = '查看' + this.moduleTitle
        }
        this.queryRemind()
        this.queryUser()
      } else {
        this.$set(this.model, 'stoptype', 1)
        for (let key of Object.keys(this.users)) {
          this.users[key] = ''
        }
        if (this.user.code === this.ownerUser.code) {
          this.users.usernames = this.ownerUser.name
          this.users.usercodes = this.ownerUser.code
        } else {
          this.users.sharenames = this.ownerUser.name
          this.users.sharecodes = this.ownerUser.code
        }
        this.$set(this.model, 'scheduletype', 'work')
        if (this.dateInfo) {
          this.assignDefaultTime()
        }
        if (this.transModel !== null) {
          // 将简单编辑页的内容传递过来
          if (this.transModel.name) this.$set(this.model, 'name', this.transModel.name)
          if (this.transModel.begintime) this.$set(this.model, 'begintime', this.transModel.begintime)
          if (this.transModel.endtime) this.$set(this.model, 'endtime', this.transModel.endtime)
          if (this.transModel.scheduletype) this.$set(this.model, 'scheduletype', this.transModel.scheduletype)
          if (this.transModel.tags) this.$set(this.model, 'tags', this.transModel.tags)
          if (this.transModel.place) this.$set(this.model, 'place', this.transModel.place)
          if (this.model.tags && this.model.tags.length > 0) {
            this.tagList = this.model.tags.split(',')
          }
        }
        this.remindList = [{ id: 0, remindtype: '1', noticetype: 'app', unit: '1', value: 2, timeValue: '09:00:00' }]
        let that = this
        setTimeout(function() {
          that.$refs.form.clearValidate()
        }, 100)
      }
      if (!this.model.begintime) {
        let now = formatDate(new Date(), 'yyyy-MM-dd')
        this.$set(this.model, 'begintime', now + ' 09:00:00')
        this.$set(this.model, 'endtime', now + ' 10:00:00')
      }
      let beginArr = this.model.begintime.split(' ')
      let endArr = this.model.endtime.split(' ')
      this.$set(this.model, 'begintimeDate', beginArr[0])
      this.$set(this.model, 'begintimeTime', beginArr[1].substring(0, 5))
      this.$set(this.model, 'endtimeDate', endArr[0])
      this.$set(this.model, 'endtimeTime', endArr[1].substring(0, 5))
    },
    // 新增时，根据日历选择的时间进行赋值
    assignDefaultTime() {
      let dateStr = this.dateInfo.dateStr
      if (dateStr.length === 10) {
        // 在月视图点击
        this.$set(this.model, 'begintime', dateStr + ' 09:00:00')
        this.$set(this.model, 'endtime', dateStr + ' 10:00:00')
      } else {
        // 增加一小时
        this.$set(this.model, 'begintime', formatDate(this.dateInfo.date, 'yyyy-MM-dd HH:mm:ss'))
        this.$set(this.model, 'endtime', formatDate(new Date(this.dateInfo.date.getTime() + 60 * 60 * 1000), 'yyyy-MM-dd HH:mm:ss'))
      }
    },
    beforeSubmit() {
      this.$set(this.model, 'begintime', `${this.model.begintimeDate} ${this.model.begintimeTime}`)
      this.$set(this.model, 'endtime', `${this.model.endtimeDate} ${this.model.endtimeTime}`)
      if (this.model.begintime > this.model.endtime) {
        this.$tap.message('开始时间不能小于结束时间', 'error')
        return false
      }
      if (this.users.usercodes.length === 0 && this.users.sharecodes.length === 0 && this.users.deptcodes.length === 0 && this.users.teamids.length === 0 && this.users.roleids.length === 0) {
        this.$tap.message('请选择日程接收人', 'error')
        return false
      }
      this.model.selectUsers = this.users
      this.model.tags = this.tagList.join(',')
      // 消息提醒处理
      let remindList = []
      this.remindList.forEach((remind, index) => {
        remindList.push({
          id: remind.id,
          remindtype: remind.remindtype,
          unit: remind.unit,
          value: remind.remindtype === '1' ? remind.value : remind.timeValue,
          noticetype: remind.noticetype,
          sortcode: index
        })
      })
      this.model.remindList = remindList
      // 周期信息处理
      if (this.model.isPeriod) {
        this.model.sourcetype = 'workTask'
        if (this.model.stoptype === 1) {
          this.$set(this.model, 'repeatcount', 0)
        } else {
          this.$set(this.model, 'stoptime', null)
        }
        // 周期任务中按月选择后。判断选择的是每月第多少天还是每月第几个周的周几
        if (this.model.periodtype === 'month') {
          if (this.model.monthrepeattype === 1) {
            // 每月第几周的周几
            this.$set(this.model, 'daysequence', this.model.monthRepeatWeek)
            this.$set(this.model, 'weeksequence', this.model.monthRepeatWeekSeq)
          } else {
            // 每月第多少天
            this.$set(this.model, 'daysequence', this.model.monthRepeatDay)
            this.$set(this.model, 'weeksequence', null)
          }
        }
      } else {
        if (this.isAdd) {
          this.$set(this.model, 'sourcetype', null)
        }
        this.$set(this.model, 'periodtype', null)
        this.$set(this.model, 'periodfrequency', null)
        this.$set(this.model, 'weeksequence', null)
        this.$set(this.model, 'daysequence', null)
        this.$set(this.model, 'repeatcount', null)
        this.$set(this.model, 'stoptime', null)
      }
      if (!this.isAdd) {
        this.url.edit = this.isEditPeriod ? this.url.editTask : this.url.editSchedule
      }
      return true
    },
    /** 执行编辑提交 */
    doEdit() {
      this.saveLoading = true
      putAction(this.url.edit, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
            this.visible = false
            if (this.isEditPeriod) this.$emit('closeAll')
            else this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    // 更改日程开始时间后，若结束时间相差不到一小时，则延后结束时间
    changeBeginTime() {
      if (this.model.begintimeTime === null) {
        return
      }
      let beginArr = this.model.begintimeTime.split(':')
      if (beginArr[0] === '23' || beginArr[0] === '24') {
        return
      }
      let endArr = this.model.endtimeTime.split(':')
      let begin = parseInt(beginArr[0]) * 60 + parseInt(beginArr[1])
      let end = parseInt(endArr[0]) * 60 + parseInt(endArr[1])
      if (end - begin <= 60) {
        let hour = (parseInt(beginArr[0]) + 1).toString()
        if (hour.length === 1) {
          hour = '0' + hour
        }
        this.$set(this.model, 'endtimeTime', `${hour}:${beginArr[1]}`)
      }
    },
    changeBeginDate() {
      if (this.model.isPeriod) {
        if (this.model.periodtype === 'month') {
          this.$refs.periodConfig.chargeMonthList()
        }
      }
    },
    // 提醒相关
    queryRemind() {
      getAction(this.url.queryRemind, { qry_sourcetype: this.qry_sourcetype, qry_sourceid: this.model.id, sidx: 'sortcode', sord: 'asc' }).then((res) => {
        if (res.success) {
          this.remindList = []
          res.result.dataList.forEach((m) => {
            this.remindList.push({
              id: m.id,
              remindtype: m.remindtype,
              noticetype: m.noticetype,
              unit: m.unit,
              value: m.remindtype === '1' ? m.value : '1',
              timeValue: m.remindtype === '2' ? m.value : '09:00:00'
            })
          })
        }
      })
    },
    // 查询已有人员
    queryUser() {
      getAction(this.url.queryUser, { qry_sourcetype: this.qry_sourcetype, qry_sourceid: this.model.id, qry_sourceflag: 'owner' }).then((res) => {
        if (res.success) {
          for (let key of Object.keys(this.users)) {
            this.users[key] = ''
          }
          res.result.forEach((m) => {
            if (m.sharetype === '5') {
              this.users.usernames = m.shareobjectsdesc
              this.users.usercodes = m.shareobjects
            } else if (m.sharetype === '1') {
              this.users.deptnames = m.shareobjectsdesc
              this.users.deptcodes = m.shareobjects
            } else if (m.sharetype === '3') {
              this.users.rolenames = m.shareobjectsdesc
              this.users.roleids = m.shareobjects
            } else if (m.sharetype === '2') {
              this.users.teamnames = m.shareobjectsdesc
              this.users.teamids = m.shareobjects
            } else if (m.sharetype === '6') {
              this.users.sharenames = m.shareobjectsdesc
              this.users.sharecodes = m.shareobjects
            }
          })
        }
      })
    },
    openPeriodList() {
      this.$refs.periodList.filtersInfo = {
        qry_sourcetype: 'workTask',
        qry_sourceid: this.model.sourceid,
        qry_sourceapp: 'work'
      }
      this.$refs.periodList.visible = true
    },
    // 标签相关
    handleClose(tag) {
      this.tagList.splice(this.tagList.indexOf(tag), 1)
    },
    // 标签相关
    showInput() {
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 标签相关
    handleInputConfirm() {
      let inputValue = this.inputValue
      if (inputValue) {
        this.tagList.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    transRefresh() {
      this.open()
      this.$emit('refresh')
    },
    closeAll() {
      this.visible = false
      this.$emit('closeAll')
    },
    checkConflict() {
      if (this.model.isPeriod) {
        this.doSubmitEdit()
        return
      }
      this.saveLoading = true
      this.$set(this.model, 'begintime', `${this.model.begintimeDate} ${this.model.begintimeTime}`)
      this.$set(this.model, 'endtime', `${this.model.endtimeDate} ${this.model.endtimeTime}`)
      let param = {
        ...this.users,
        begintime: this.model.begintime,
        endtime: this.model.endtime
      }
      if (!this.isAdd) {
        param.id = this.model.id
      }
      getAction(this.url.queryConflict, param)
        .then((res) => {
          if (res.success) {
            this.conflictList = res.result
            if (res.result.length > 0) {
              this.$confirm('所选日程接收人中存在时间冲突，是否继续保存？', '提示', {
                confirmButtonText: '查看冲突',
                cancelButtonText: '忽略冲突继续保存',
                type: 'warning'
              })
                .then((_) => {
                  // 查看冲突
                  this.$refs.conflictList.visible = true
                  this.saveLoading = false
                })
                .catch((_) => {
                  this.saveLoading = false
                  // 忽略继续保存
                  this.doSubmitEdit()
                })
            } else {
              this.saveLoading = false
              // 没有冲突
              this.doSubmitEdit()
            }
          } else {
            this.saveLoading = false
            // 调用接口出错了
            this.conflictList = []
            this.doSubmitEdit()
          }
        })
        .catch((_) => {
          this.saveLoading = false
          // 调用接口出错了
          this.conflictList = []
          this.doSubmitEdit()
        })
    }
  }
}
</script>
<style scoped lang="scss">
.tag-container {
  .el-tag {
    margin-right: 5px;
  }
}
.color-block {
  display: inline-block;
  height: 15px;
  width: 15px;
}
.input-with-select {
  .el-select {
    width: 80px;
  }
}
</style>
